package com.etc.service.impl.sensor;

import com.etc.entity.sensor.BizSensorConfig;
import com.etc.repository.sensor.BizSensorConfigRepository;
import com.etc.result.CodeMessage;
import com.etc.result.ResultBean;
import com.etc.service.secsor.IBizSensorConfigService;
import com.etc.utils.JxlExcelUtil;
import com.etc.utils.PoiExcelUtil;
import com.etc.utils.StringUtil;
import com.etc.vo.sensor.BizSensorConfigVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author : DDS
 * @Description : 传感器字典表模型 业务层实现类
 * @Date: 2019-11-28 17:47
 */
@Slf4j
@Service
public class BizSensorConfigServiceImpl implements IBizSensorConfigService {

    @Autowired
    private BizSensorConfigRepository bizSensorConfigRepository;

    /**
     * 分页查询
     *
     * @param pageNum  所查询的页数
     * @param pageSize 每页展示信息的数量
     * @return 统一的返回ResultBean
     */
    @Override
    public ResultBean findCriteria(BizSensorConfigVo bizSensorConfigVo,
                                   Integer pageNum, Integer pageSize) {

        //获取pageable 添加所查询的页数以及每页展示信息的数量
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Specification<BizSensorConfig> spec = new Specification<BizSensorConfig>() {
            @Override
            public Predicate toPredicate(Root<BizSensorConfig> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> pr = new ArrayList<>();
                if (StringUtil.isNotNull(bizSensorConfigVo)) {
                    if (StringUtil.isNotNull(bizSensorConfigVo.getType())) {
                        pr.add(criteriaBuilder.equal(root.get("type"), bizSensorConfigVo.getType()));
                    }
                    if (StringUtil.isNotNull(bizSensorConfigVo.getBridgeSpan())) {
                        pr.add(criteriaBuilder.equal(root.get("bridgeSpan"), bizSensorConfigVo.getBridgeSpan()));
                    }
                    if (StringUtil.isNotNull(bizSensorConfigVo.getSensorPosition())) {
                        pr.add(criteriaBuilder.equal(root.get("sensorPosition"), "%" + bizSensorConfigVo.getSensorPosition() + "%"));
                    }
                    return criteriaBuilder.and(pr.toArray(new Predicate[pr.size()]));
                }
                return null;
            }
        };

        try {
            //通过JPA查询到bizSensorConfig表中所有的数据
            Page<BizSensorConfig> bizSensorConfigPage = bizSensorConfigRepository.findAll(spec, pageable);
            //调用组装方法
            Page<BizSensorConfigVo> bizSensorConfigVoPage = entityAssemble(bizSensorConfigPage, pageable);
            return ResultBean.success(bizSensorConfigVoPage);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 根据id删除数据
     *
     * @param id 数据id
     * @return 统一的返回ResultBean
     */
    @Override
    public ResultBean deleteById(String id) {

        try {
            bizSensorConfigRepository.deleteById(id);
            return ResultBean.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResultBean.error(CodeMessage.DELETE_DEFEATED.getCode(), CodeMessage.DELETE_DEFEATED.getMassage());
        }

    }

    /**
     * 根据id更新数据
     *
     * @param bizSensorConfig 更新的数据信息
     * @return 统一的返回ResultBean
     */
    @Override
    public ResultBean update(BizSensorConfig bizSensorConfig) {
        try {
            bizSensorConfigRepository.save(bizSensorConfig);
            return ResultBean.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResultBean.error(CodeMessage.UPDATE_DEFEATED.getCode(), CodeMessage.UPDATE_DEFEATED.getMassage());
        }
    }

    /**
     * 上传Excel
     *
     * @return 统一的返回ResultBean
     */
    @Override
    public ResultBean toExcel(String filename, MultipartFile file) throws IOException {

        InputStream input = file.getInputStream();
        List<BizSensorConfig> bizSensorConfigs = PoiExcelUtil.toLead(filename, input);
        try {
            bizSensorConfigRepository.saveAll(bizSensorConfigs);
            return ResultBean.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResultBean.error(CodeMessage.UPDATE_DEFEATED.getCode(), CodeMessage.UPDATE_DEFEATED.getMassage());
        }
    }

    /**
     * 从数据库导出Excel
     *
     * @return 统一的返回ResultBean
     */
    @Override
    public ResultBean downExcel() {
        try {
            List<BizSensorConfig> bizSensorConfigs = bizSensorConfigRepository.findAll();
            return JxlExcelUtil.downExcel(bizSensorConfigs);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResultBean.error(CodeMessage.FIND_DEFEATED.getCode(), CodeMessage.FIND_DEFEATED.getMassage());
        }
    }

    /**
     * 查询所有数据
     *
     * @return 统一的的返回ResultBean
     */
    @Override
    public ResultBean findById(String id) {
        try {
            Optional<BizSensorConfig> bizSensorConfig = bizSensorConfigRepository.findById(id);
            if (StringUtil.isNotNull(bizSensorConfig)) {
                return ResultBean.success(bizSensorConfig.get());
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResultBean.error(CodeMessage.FIND_DEFEATED.getCode(), CodeMessage.FIND_DEFEATED.getMassage());
        }
    }

    /**
     * 组装返回的实体类
     *
     * @param page
     * @param pageable
     * @return
     */
    public static Page<BizSensorConfigVo> entityAssemble(Page<BizSensorConfig> page, Pageable pageable) {

        //创建一个List容器
        List<BizSensorConfigVo> bizSensorConfigVos = new ArrayList<>();

        //循环遍历bizSensorConfigPage中的数据
        for (BizSensorConfig bizSensorConfig1 : page) {
            //实例化 传感器字典表模型组装
            BizSensorConfigVo bizSensorConfigVo = new BizSensorConfigVo();
            //将遍历出的数据组装到bizSensorConfig中
            bizSensorConfigVo.setId(bizSensorConfig1.getId());
            bizSensorConfigVo.setType(bizSensorConfig1.getType());
            bizSensorConfigVo.setSensorNumber(bizSensorConfig1.getSensorNumber());
            bizSensorConfigVo.setSensorPosition(bizSensorConfig1.getSensorPosition());
            bizSensorConfigVo.setBridgeSpan(bizSensorConfig1.getBridgeSpan());
            //将组装好的数据添加到List容器中
            bizSensorConfigVos.add(bizSensorConfigVo);
        }
        //创建一个自定义的Page 参数(组装的容器bizSensorConfigs，分页的信息pageable，数据总数bizSensorConfigPage.getTotalElements())
        Page<BizSensorConfigVo> bizSensorConfigVoPage = new PageImpl<BizSensorConfigVo>(bizSensorConfigVos,
                pageable, page.getTotalElements());
        return bizSensorConfigVoPage;

    }

}
